package cn.hom1.web;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 文件上传
 *
 * @author iksen
 * @date 2019-01-18 14:42
 */
@Controller
public class UploadController {

  @GetMapping("/")
  public String index(){
    return "upload";
  }

  @GetMapping("/more")
  public String more(){
    return "uploadMore";
  }

  @GetMapping("uploadStatus")
  public String uploadStatus(){
    return "uploadStatus";
  }

  @PostMapping("/upload")
  public String singleFileUpload(@RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes){
    if (file.isEmpty()) {
      redirectAttributes.addFlashAttribute("message", "请选择要上载的文件");
      return "redirect:uploadStatus";
    }
    try {
      // 获取文件并将其保存到某个位置
      byte[] bytes = file.getBytes();
      //文件本地存储地址
      Path path = Paths.get("upload/" + file.getOriginalFilename());
      Files.write(path, bytes);

      redirectAttributes.addFlashAttribute("message",
          "您已成功上传 '" + file.getOriginalFilename() + "'");
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "redirect:/uploadStatus";
  }

  @PostMapping("/uploadMore")
  public String moreFileUpload(@RequestParam("file") MultipartFile[] files,
      RedirectAttributes redirectAttributes){
    if (files.length == 0) {
      redirectAttributes.addFlashAttribute("message", "请选择要上载的文件");
      return "redirect:uploadStatus";
    }
    for (MultipartFile file : files){
      try {
        //获取文件并将其保存到某个位置
        byte[] bytes = file.getBytes();
        Path path = Paths.get("upload/" + file.getOriginalFilename());
        Files.write(path, bytes);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    redirectAttributes.addFlashAttribute("message", "您已成功上传所有");
    return "redirect:/uploadStatus";
  }
}
